package sdk.webview.fmc.com.fmcsdk.view;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.LinkMovementMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.method.TransformationMethod;
import android.text.style.ClickableSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.RequestBody;
import rx.Observable;
import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.activity.CommonWebActivity;
import sdk.webview.fmc.com.fmcsdk.activity.LoginActivity;
import sdk.webview.fmc.com.fmcsdk.base.BaseData;
import sdk.webview.fmc.com.fmcsdk.base.UserApi;
import sdk.webview.fmc.com.fmcsdk.bean.CheckByUnamepwdResponse;
import sdk.webview.fmc.com.fmcsdk.bean.IconBean;
import sdk.webview.fmc.com.fmcsdk.bean.SysKeyDescBean;
import sdk.webview.fmc.com.fmcsdk.util.AESUtil;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.StringUtils;
import sdk.webview.fmc.com.fmcsdk.util.ToastUtils;
import sdk.webview.fmc.com.fmcsdk.util.Url;
import sdk.webview.fmc.com.fmcsdk.util.UserHelper;
import sdk.webview.fmc.com.fmcsdk.util.XLog;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.observer.ApiFactory;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.observer.ResponseTransformer;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.subscriber.ResponseSubscriber;


/**
 * 修改密码的弹窗
 */
public class EditPwdDialog extends Dialog {
    private int language = 0; //0 简体  1  英文   2 繁体
    private Context context;

    private TextView confirm;
    private TextView tv_zhuyi_content, tv_error_tip, tv_pwd_guize;
    private EditText ev_yuan_pwd, ev_new_pwd, ev_again_new_pwd;
    private ImageView iv_yuanpwd_yanjing, iv_newpwd_yanjing, iv_again_newpwd_yanjing;

    private LinearLayout ll_error_tip;
    private RelativeLayout rv_yuan_pwd, rv_yuanyin;

    private ClickiInterface mClickiInterface;

    private SharedPreferences sharedPrefs;

    private String code; //

    private StringBuffer stringBuffer = new StringBuffer();

    private String pattrenPwd;

    private String username;

    private String type = "0"; //1 是忘记密码  0不是

    //只有提示内容的消息框
    public EditPwdDialog(Context context, String code, String username, ClickiInterface clickiInterface) {
        super(context, R.style.Dialog);
        this.context = context;
        this.code = code;
        this.username = username;
        this.mClickiInterface = clickiInterface;
        sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        language = sharedPrefs.getInt("lang", 0);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_pwd_dialog);
        confirm = (TextView) findViewById(R.id.confirm);
        TextView cancel = (TextView) findViewById(R.id.cancel);

        tv_zhuyi_content = (TextView) findViewById(R.id.tv_zhuyi_content);
        tv_error_tip = (TextView) findViewById(R.id.tv_error_tip);
        tv_pwd_guize = (TextView) findViewById(R.id.tv_pwd_guize);
        ev_yuan_pwd = (EditText) findViewById(R.id.ev_yuan_pwd);
        ev_new_pwd = (EditText) findViewById(R.id.ev_new_pwd);
        ev_again_new_pwd = (EditText) findViewById(R.id.ev_again_new_pwd);
        ll_error_tip = (LinearLayout) findViewById(R.id.ll_error_tip);
        rv_yuan_pwd = (RelativeLayout) findViewById(R.id.rv_yuan_pwd);

        iv_yuanpwd_yanjing = (ImageView) findViewById(R.id.iv_yuanpwd_yanjing);
        iv_newpwd_yanjing = (ImageView) findViewById(R.id.iv_newpwd_yanjing);
        iv_again_newpwd_yanjing = (ImageView) findViewById(R.id.iv_again_newpwd_yanjing);

        rv_yuanyin = (RelativeLayout) findViewById(R.id.rv_yuanyin);

        confirm.setOnClickListener(new clickListener());
        cancel.setOnClickListener(new clickListener());

        iv_yuanpwd_yanjing.setOnClickListener(new clickListener());
        iv_newpwd_yanjing.setOnClickListener(new clickListener());
        iv_again_newpwd_yanjing.setOnClickListener(new clickListener());

        //试着提示框的位置和大小
        Window dialogWindow = getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics d = context.getResources().getDisplayMetrics(); // 获取屏幕宽、高
        lp.width = (int) (d.widthPixels * 0.9);
        dialogWindow.setAttributes(lp);
        this.setCanceledOnTouchOutside(false);

        initMsg();

        if ("WEAK_PWD".equals(code)) {
            rv_yuan_pwd.setVisibility(View.GONE);
        } else {
            rv_yuan_pwd.setVisibility(View.VISIBLE);
        }
    }


    public void setType(String type) {
        this.type = type;
        if ("1".equals(type)) {
            rv_yuan_pwd.setVisibility(View.GONE);
        } else {
            rv_yuan_pwd.setVisibility(View.VISIBLE);
        }
    }

    //是否显示原因
    public void setIsShowYuan(String type) {
        if ("1".equals(type)) {
            rv_yuanyin.setVisibility(View.GONE);
        } else {
            rv_yuanyin.setVisibility(View.VISIBLE);
        }
    }

    private void initMsg() {
        getTips("CHG_PWD_REASON", code);  //获取修改密码的原因

        //type=PWD_COMPLAXITY 获取 密码复杂度
        getTips("PWD_COMPLEXITY", UserHelper.getSysSettingsValueBycode("PWD_COMPLEXITY"));  //获取密码的复杂度
        //PWD_LEN 密码长度(位)

//        getTips("PWD_COMPLEXITY"); //密码复杂度
//        getTips("PWD_RULE_TIPS");


        // "value": "8,20"
        stringBuffer.append("1." + context.getResources().getString(R.string.mimabixushi) + UserHelper.getSysSettingsValueBycode("PWD_LEN")
                + context.getResources().getString(R.string.zhijian) + "\n");

        tv_pwd_guize.setText(stringBuffer);
    }

    String tipstr;

    private class clickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            int id = v.getId();
            if (id == R.id.confirm) {
                ll_error_tip.setVisibility(View.GONE);

                String yuanmima = ev_yuan_pwd.getText().toString().trim();
                String newpwd = ev_new_pwd.getText().toString().trim();
                String newpwdagain = ev_again_new_pwd.getText().toString().trim();

                if (!"1".equals(type)) {
                    if (TextUtils.isEmpty(yuanmima)) {
                        ToastUtils.showShort(context, context.getString(R.string.hint_setting_original_psd));
                        return;
                    }
                }


                if (TextUtils.isEmpty(newpwd)) {
                    ToastUtils.showShort(context, context.getString(R.string.hint_setting_input_newpsd));
                    return;
                }

                if (TextUtils.isEmpty(newpwdagain)) {
                    ToastUtils.showShort(context, context.getString(R.string.hint_setting_agine_input_newpsd));
                    return;
                }

                if (!newpwd.equals(newpwdagain)) {
                    ToastUtils.showShort(context, context.getString(R.string.new_pwd_buyiyang));
                    return;
                }

                if (!"1".equals(type)) {
                    if (yuanmima.equals(newpwd)) {
                        ToastUtils.showShort(context, context.getString(R.string.msg_setting_psdequalsodlpsw));
                        return;
                    }
                }

                int[] pwd_lens = StringUtils.CommaSeparatedStringToIntArray(UserHelper.getSysSettingsValueBycode("PWD_LEN"));
                if (pwd_lens != null) {
                    if (newpwd.length() < pwd_lens[0] || newpwd.length() > pwd_lens[1]) {
                        ll_error_tip.setVisibility(View.VISIBLE);
                        tv_error_tip.setText(context.getResources().getString(R.string.mimabixushi) + UserHelper.getSysSettingsValueBycode("PWD_LEN")
                                + context.getResources().getString(R.string.zhijian));
                        return;
                    }
                }

                if (!StringUtils.isPwdPartten(newpwd, pattrenPwd)) {
                    ll_error_tip.setVisibility(View.VISIBLE);
                    tv_error_tip.setText(tipstr);
                    return;
                }

                editPwd(yuanmima, newpwd);
            } else if (id == R.id.cancel) {
                mClickiInterface.clickCancel(code);
            } else if (id == R.id.iv_yuanpwd_yanjing) {
                isShowPassword(isHideOne, ev_yuan_pwd, iv_yuanpwd_yanjing);
                isHideOne = isHideOne ? false : true;
            } else if (id == R.id.iv_newpwd_yanjing) {
                isShowPassword(isHideTwo, ev_new_pwd, iv_newpwd_yanjing);
                isHideTwo = isHideTwo ? false : true;
            } else if (id == R.id.iv_again_newpwd_yanjing) {
                isShowPassword(isHideThree, ev_again_new_pwd, iv_again_newpwd_yanjing);
                isHideThree = isHideThree ? false : true;
            }

        }

    }


    public interface ClickiInterface {
        void clickSure(String username, String loginOldPwd, String loginNewPwd);

        void clickCancel(String pwdChangeDec);
    }

    /**
     * accessToken	Long	是	操作令牌
     * username	String	是	用户名
     * loginOldPwd	String	否	旧密码
     * loginNewPwd	String	否	新密码
     * encrypted	String	否	是否加密	3  固定写死
     */
    private void editPwd(String loginOldPwd, String loginNewPwd) {
        mClickiInterface.clickSure(username, loginOldPwd, loginNewPwd);
    }

    /**
     * @param type * PWD_COMPLEXITY  密码复杂度   PWD_RULE_TIPS 密码规则提示语   CHG_PWD_REASON 密码修改的原因
     *             * http://192.168.200.78/sys/keyDesc/list/api?type=CHG_PWD_REASON
     */
    private void getTips(final String type, final String code) {
        ApiFactory.getFactory().create(UserApi.class).someTipsOrDec(sharedPrefs.getString(Constant.BASE_ADDRESS_URL,
                "") + Url.KEYDESC + type + "&code=" + code)
                .compose(new ResponseTransformer())
                .subscribe(new ResponseSubscriber<SysKeyDescBean>() {
                    @Override
                    public void success(SysKeyDescBean baseData) {
                        List<SysKeyDescBean.SettingInfo> records = baseData.getRecords();
                        if (records != null) {
                            if ("CHG_PWD_REASON".equals(type)) {
                                if (language == 2) {
                                    tv_zhuyi_content.setText(records.get(0).getDescriptionOth());
                                } else if (language == 1) {
                                    tv_zhuyi_content.setText(records.get(0).getDescriptionEn());
                                } else {
                                    tv_zhuyi_content.setText(records.get(0).getDescription());
                                }
                            } else if ("PWD_COMPLEXITY".equals(type)) {
                                if (language == 2) {
                                    tipstr = records.get(0).getDescriptionOth();
                                    stringBuffer.append("2." + records.get(0).getDescriptionOth() + "\n");
                                } else if (language == 1) {
                                    tipstr = records.get(0).getDescriptionEn();
                                    stringBuffer.append("2." + records.get(0).getDescriptionEn() + "\n");
                                } else {
                                    tipstr = records.get(0).getDescription();
                                    stringBuffer.append("2." + records.get(0).getDescription() + "\n");
                                }
                                stringBuffer.append(context.getResources().getString(R.string.mimabutong));
                                tv_pwd_guize.setText(stringBuffer);

                                pattrenPwd = records.get(0).getSpecialLabel();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }

                    @Override
                    public void onRequestAgain() {

                    }

                });
    }

    private boolean isHideOne = false;
    private boolean isHideTwo = false;
    private boolean isHideThree = false;

    private void isShowPassword(boolean isHide, EditText editText, ImageView imageView) {
        if (isHide == false) {
            //R.mipmap.password_show是表示显示密码的“眼睛”图标
            imageView.setImageResource(R.mipmap.kaiyan);
            //密文
            HideReturnsTransformationMethod method1 = HideReturnsTransformationMethod.getInstance();
            editText.setTransformationMethod(method1);
        } else {
            //R.mipmap.password_miss是表示隐藏密码的“眼睛+斜杠”图标
            imageView.setImageResource(R.mipmap.miyan);
            //密文
            TransformationMethod method2 = PasswordTransformationMethod.getInstance();
            editText.setTransformationMethod(method2);
        }
        //重置光标位置
        int index = editText.getText().toString().length();
        editText.setSelection(index);
    }
}
